package org.ajaxgroovyshell;

import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;

import org.jboss.util.naming.NonSerializableFactory;
import org.jboss.system.ServiceMBeanSupport;


public class GroovyShellService extends ServiceMBeanSupport implements GroovyShellServiceMBean {

	private static final String JNDI_NAME = "GroovyShellService";
	
	ConsoleRunner cr;
	
	public ConsoleRunner getConsoleRunner(){
		return cr;
	}
	
	protected void startService() throws Exception {
		if (cr == null){
			cr = new ConsoleRunner();
			cr.start();
			rebind();
		}
	}
	
	protected void stopService() throws Exception {
		unbind(JNDI_NAME);
		cr.interrupt();
	}
	
    private void rebind() throws NamingException {
        InitialContext rootCtx = new InitialContext();
        try {
            Name fullName = rootCtx.getNameParser("").parse(JNDI_NAME);
            NonSerializableFactory.rebind(fullName, this, true);
        } finally {
            rootCtx.close(); 
        }
    }
    
    private void unbind(String jndiName) throws NamingException {
        InitialContext rootCtx = new InitialContext();
        try {
            rootCtx.unbind(jndiName);
            NonSerializableFactory.unbind(jndiName);
        } finally {
            rootCtx.close(); 
        }
    }
}
